﻿var ns = namespace("kaskelot.sp.ui");

ns.formutils = function () {

    function showForm(selector, open_function, ok_function, dialogWidth) {

        disableBackspace();

        $(selector).dialog({
			position: ['top', 100],
            width: dialogWidth,
            //height: 800,
            buttons: {
                OK: function () {
                    if (validate(selector))
                        ok_function();
                },
                Avbryt: function () {
                    $(this).dialog("close");
                }
            },
            open: function () {
                $(".ui-widget-overlay").appendTo($("form"));
                $(this).parent().appendTo($("form"));
                initControls(selector);
                open_function();

                $(".form").attr("tabindex", "0");

                $('.form textarea').keypress(function (event) {
                    if (event.which == 13) {
                        event.stopPropagation();
                    }
                });

                $(".form").keypress(function (event) {
                	if (event.which == 13) {
                		event.preventDefault();
                	}
                });

                $(".form").keypress(function (event) {
                	if (event.which == 13) {
                		$(".ui-dialog-buttonset button:first").click();
                	}
                });

                $(".required-star").remove();
                $(".required").not(".error").after("<span class=\"required-star\"> *</span>");
            },
            close: function () {
                destroyAnyTinyMCE(this);
                $(selector).remove();
                enableBackspace();
            }
        });
    }

    function showCloseableForm(selector, open_function, dialogWidth) {

        disableBackspace();

        $(selector).dialog({
            width: dialogWidth,
            buttons: {
                Stäng: function () {
                    $(this).dialog("close");
                }
            },
            open: function () {
                $(".ui-widget-overlay").appendTo($("form"));
                $(this).parent().appendTo($("form"));
                initControls(selector);
                open_function();
            },
            close: function () {
                $(selector).remove();
                enableBackspace();
            }
        });
    }

    function initControls(selector) {

        //initTinyMCE(selector + " textarea:visible");

        //$(selector + " .singlepicker:visible").singlepicker();
        //$(selector + " .multipicker:visible").multipicker();
        //$(selector + " .datepicker").datepicker();
        //$(selector + " .monthpicker").monthpicker();
        //$(selector + " .tree-picker").treepicker();
    }

    function initTinyMCE(selector) {
        $(selector).tinymce({
            script_url: '/_layouts/15/Precio.NGO.UI/Scripts/Libraries/tiny_mce/tiny_mce.js',
            theme: 'advanced',
            content_css: '/_layouts/BRC.PIMS.UI/Styles/jHtmlArea.Editor.css',
            mode: 'none',
            plugins: 'paste',
            theme_advanced_buttons1: "bold,italic,underline,|,undo,redo,|,removeformat",
            theme_advanced_buttons2: "",
            theme_advanced_buttons3: "",
            theme_advanced_buttons4: "",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "none",
            //theme_advanced_path_location: "none",
            paste_auto_cleanup_on_paste: true,
            paste_remove_spans: true
        });
    }

    function getAndShowForm(options) {

        var defaults = {
            params: {},
            selector: "",
            openFunction: function () { },
            okFunction: function () { },
            dialogWidth: 710,
            closable: false
        }

        var settings = $.extend({}, defaults, options);

        if (settings.params.formName == undefined)
            $.error("form name is not set");

        var method = "GetForm";

        $.ajax({
            url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientFormService.svc/" + method,
            type: "GET",
            processData: true,
            contentType: "application/json",
            dataType: "json",
            cache: false,
            data: settings.params,
            success:
                function (resp) {
                    if (!resp[method + "Result"].HasError) {

                        $("#form-container").html(resp[method + "Result"].Data);

                        if (!settings.closable)
                            showForm(settings.selector, settings.openFunction, settings.okFunction, settings.dialogWidth);
                        else
                            showCloseableForm(settings.selector, settings.openFunction, settings.dialogWidth);
                    }
                    else {
                        kaskelot.sp.ui.prompts.showErrorPrompt(resp[method + "Result"].ErrorMessage);
                    }
                },
            error:
                function (xhr) {
                    kaskelot.sp.ui.prompts.showErrorPrompt(xhr.responseText);
                }
        });
    }

    function getForm(options, callback, index) {
    	var defaults = {
    		params: {},
    		selector: "",
    		openFunction: function () { },
    		okFunction: function () { },
    		dialogWidth: 710,
    		closable: false
    	}

    	var settings = $.extend({}, defaults, options);

    	if (settings.params.formName == undefined)
    		$.error("form name is not set");

    	var method = "GetForm";

    	$.ajax({
    		url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientFormService.svc/" + method,
    		type: "GET",
    		processData: true,
    		contentType: "application/json",
    		dataType: "json",
    		cache: false,
    		data: settings.params,
    		success:
                function (resp) {
                	if (!resp[method + "Result"].HasError) {
                		callback(index, resp[method + "Result"].Data);
                	}
                	else {
                		kaskelot.sp.ui.prompts.showErrorPrompt(resp[method + "Result"].ErrorMessage);
                	}
                },
    		error:
                function (xhr) {
                	kaskelot.sp.ui.prompts.showErrorPrompt(xhr.responseText);
                }
    	});
    }

    function getAndShowDisplayForm(options) {

        var defaults = {
            params: {},
            selector: "",
            openFunction: function () { },
            dialogWidth: 685
        }

        var settings = $.extend({}, defaults, options);

        if (settings.params.formName == undefined)
            $.error("form name is not set");

        var method = "GetDisplayForm";

        $.ajax({
            url: clientContext.WebServerRelativeUrl + "_vti_bin/Precio.NGO.Resources/ClientFormService.svc/" + method,
            type: "GET",
            processData: true,
            contentType: "application/json",
            dataType: "json",
            cache: false,
            data: settings.params,
            success:
                function (resp) {
                    if (!resp[method + "Result"].HasError) {

                        $("#form-container").html(resp[method + "Result"].Data);

                        showCloseableForm(settings.selector, settings.openFunction, settings.dialogWidth);
                    }
                    else {
                        precio.ngo.prompts.showErrorPrompt(resp[method + "Result"].ErrorMessage);
                    }
                },
            error:
                function (xhr) {
                    precio.ngo.prompts.showErrorPrompt(xhr.responseText);
                }
        });
    }

    function getAndShowListing(options) {
        var defaults = {
            params: {},
            selector: "",
            openFunction: function () { },
            dialogWidth: 685
        }

        var settings = $.extend({}, defaults, options);

        if (settings.params.formName == undefined)
            $.error("form name is not set");

        var method = "GetListing";

        $.ajax({
            url: clientContext.WebServerRelativeUrl + "_vti_bin/Precio.NGO.Resources/ClientFormService.svc/" + method,
            type: "GET",
            processData: true,
            contentType: "application/json",
            dataType: "json",
            cache: false,
            data: settings.params,
            success:
                function (resp) {
                    if (!resp[method + "Result"].HasError) {

                        $("#form-container").html(resp[method + "Result"].Data);

                        showCloseableForm(settings.selector, settings.openFunction, settings.dialogWidth);
                    }
                    else {
                        precio.ngo.prompts.showErrorPrompt(resp[method + "Result"].ErrorMessage);
                    }
                },
            error:
                function (xhr) {
                    precio.ngo.prompts.showErrorPrompt(xhr.responseText);
                }
        });
    }


    function disableBackspace() {
        $('body').keydown(function (e) {
            if (e.keyCode === 8) {
                var element = e.target.nodeName.toLowerCase();
                if (element != 'input' && element != 'textarea') {
                    return false;
                }
            }
        });
    }

    function enableBackspace() {
        $('body').unbind('keydown');
    }

    function destroyAnyTinyMCE(target) {
        $(target).find("span.mceEditor").each(function () {
            var id = $(this).prev().attr('id');

            if (id == undefined)
                id = $(this).prev().prev().attr('id');

            tinymce.execCommand('mceRemoveControl', true, id);
        });
    }

    function validate(selector) {

    	var isValid = true;
    	$(selector).find(":input").not("input:hidden").each(function () { // if $validator.defaults.ignore is change, the not claus must be changed here
    		if (!$(this).valid())
    			isValid = false;
    	});

    	$(".required-star").remove();
    	$(".required").not(".error").after("<span class=\"required-star\"> *</span>");

        return isValid;
    }

    function getObject(selector) {
        var obj = {};

        $(selector + " :input[id]").each(function () {
            if($(this).is("select[multiple='multiple'].multiselect")) {
                var values = [];

                $(this).find("[selected='selected']").each(function () {
                    values.push(this.value);
                });

                obj[$(this).attr("id")] = values;

                if (values.length === 0)
                    obj[$(this).attr("id")] = $(this).val();
            }

            else if ($(this).is("[type='checkbox']"))
                obj[$(this).attr("id")] = $(this).is(":checked");
            else
                obj[$(this).attr("id")] = $(this).val() != null ? $(this).val() : [];
        });

        return obj;
    }

    function showError(select, errorMessage) {
        kaskelot.sp.ui.prompts.showErrorPrompt(errorMessage);
        $(select).parent().unblock();
    }

    function fixOverlay() {
        setTimeout(function () {
            $(".ui-widget-overlay").css('height', $(document).height());
        }, 500);
    }

    function getAndShowPostForm(options) {

    	var defaults = {
    		params: {},
    		selector: "",
    		openFunction: function () { },
    		okFunction: function () { },
    		dialogWidth: 710,
    		closable: false
    	}

    	var settings = $.extend({}, defaults, options);

    	if (settings.params.formName == undefined)
    		$.error("form name is not set");

    	var method = "GetFormByPost";
    	$.ajax({
    		url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientFormService.svc/" + method,
    		data: JSON.stringify(settings.params),
    		type: "POST",
    		processData: false,
    		contentType: "application/json",
    		dataType: "json",
    		success:
                function (resp) {
                	if (!resp[method + "Result"].HasError) {

                		$("#form-container").html(resp[method + "Result"].Data);

                		if (!settings.closable)
                			showForm(settings.selector, settings.openFunction, settings.okFunction, settings.dialogWidth);
                		else
                			showCloseableForm(settings.selector, settings.openFunction, settings.dialogWidth);
                	}
                	else {
                		kaskelot.sp.ui.prompts.showErrorPrompt(resp[method + "Result"].ErrorMessage);
                	}
                },
    		error:
                function (xhr) {
                	kaskelot.sp.ui.prompts.showErrorPrompt(xhr.responseText);
                }
    	});
    }

    return {
        getAndShowForm: getAndShowForm,
        getAndShowDisplayForm: getAndShowDisplayForm,
        getAndShowListing: getAndShowListing,
        getObject: getObject,
        initTinyMCE: initTinyMCE,
        showError: showError,
        fixOverlay: fixOverlay,
        getForm: getForm,
		getAndShowPostForm: getAndShowPostForm
    }

}();